import subprocess
import sys
import os

print("正在尝试安装langchain包...")
print(f"当前Python版本: {sys.version}")
print(f"当前路径: {os.getcwd()}")

# 定义多个镜像源
mirrors = [
    "https://pypi.douban.com/simple",  # 豆瓣
    "https://mirrors.aliyun.com/pypi/simple",  # 阿里云
    "https://pypi.mirrors.ustc.edu.cn/simple",  # 中科大
    "https://repo.huaweicloud.com/repository/pypi/simple",  # 华为云
]

def install_with_mirror(mirror):
    try:
        print(f"\n尝试使用镜像源: {mirror}")
        # 设置更长的超时时间
        result = subprocess.run(
            [sys.executable, "-m", "pip", "install", "langchain", 
             "-i", mirror, 
             "--default-timeout=120", 
             "--trusted-host", mirror.split("//")[1].split("/")[0]],
            capture_output=True, 
            text=True,
            timeout=300  # 5分钟超时
        )
        if result.returncode == 0:
            print("✅ langchain包安装成功!")
            return True
        else:
            print(f"❌ 安装失败，错误信息: {result.stderr[:300]}...")
            return False
    except Exception as e:
        print(f"❌ 安装过程中出错: {str(e)}")
        return False

# 尝试所有镜像源
for mirror in mirrors:
    if install_with_mirror(mirror):
        break
else:
    # 如果所有镜像源都失败了
    print("\n❌ 所有镜像源都安装失败。请尝试以下备选方案:")
    print("1. 检查网络连接是否正常")
    print("2. 稍后重试安装命令")
    print("3. 考虑使用代理服务器")
    print("\n备用方法: 创建requirements.txt并下载离线包")
    # 创建requirements.txt文件
    with open("requirements.txt", "w") as f:
        f.write("langchain\n")
    print("已创建requirements.txt文件")
    print("\n离线安装命令参考:")
    print("# 在有网络的环境下下载:")
    print("pip download -r requirements.txt -d packages")
    print("# 然后在目标环境安装:")
    print("pip install --no-index --find-links=packages -r requirements.txt")

# 验证安装
print("\n正在验证langchain安装...")
try:
    import langchain
    from langchain.core.messages import AnyMessage
    print(f"✅ 验证成功! langchain版本: {langchain.__version__}")
    print("AnyMessage类已成功导入")
except ImportError as e:
    print(f"❌ 验证失败: {str(e)}")
    print("langchain包未成功安装或导入")